package ricelee.demo.rxjava;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class ThreadActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = ThreadActivity.class.getSimpleName();
    private Button threadBtn;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thread);
        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        getSupportActionBar().setTitle("线程控制");
        threadBtn = (Button) findViewById(R.id.btn_thread);
        threadBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_thread) {
            update();
        }
    }


    private void update() {
        final ProgressDialog progressDialog = new ProgressDialog(ThreadActivity.this);
        progressDialog.setTitle("加载中。。。");
        progressDialog.show();
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
                Log.i(TAG, "observable -- onNext" + Thread.currentThread().getName());
                Thread.currentThread().sleep(1000);
                emitter.onNext(1);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Integer integer) {
                        Log.i(TAG, "Observer -- onNext" + Thread.currentThread().getName());
                        progressDialog.setTitle(String.valueOf(integer));
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        Log.i(TAG, "Observer -- onComplete" + Thread.currentThread().getName());
//                        progressDialog.setTitle("加载完成");
                        progressDialog.dismiss();
                    }
                });

    }


}
